﻿using System.Security.Cryptography;
using UnityEngine;

// Lua文件写入类
// 文件头首先会写入MD5校验码
public class LuaFileWriter
{
    private EPacket m_FileEPacket = new EPacket(Parser.STRING_MAXLENGTH);

    // 写入Boolean
    public void WriteBoolean(bool bVal)
    {
        m_FileEPacket.WriteBoolean(bVal);
    }

    // 写入Int
    public void WriteInt(int nVal)
    {
        m_FileEPacket.WriteInt(nVal);
    }

    // 写入Float
    public void WriteFloat(float nVal)
    {
        m_FileEPacket.WriteFloat(nVal);
    }

    // 写入String
    public void WriteString(string strVal)
    {
        m_FileEPacket.WriteString(strVal);
    }

    // 存储文件
    public bool Save(string filename)
    {
        filename = Application.persistentDataPath + "/" + filename;
        FileLoader loader = new FileLoader();
        if (!loader.Load(filename, FileLoader.FILE_MODE.TYPED_CLEAR_WRITE))
        {
            loader.UnLoad();
            loader = null;
            return false;
        }

        byte[] buffer = m_FileEPacket.GetPacketBuffer();
        if (buffer.Length <= 0)
        {
            loader.UnLoad();
            loader = null;
            return true;
        }

        if (!loader.Write(buffer, buffer.Length))
        {
            buffer = null;
            loader.UnLoad();
            loader = null;
            return false;
        }

        // 计算buffer的MD5
        // 文件结尾添加对应的MD5进行文件校验
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] md5Data = md5.ComputeHash(buffer, 0, buffer.Length);
        if (!loader.Write(md5Data, md5Data.Length))
        {
            md5Data = null;
            buffer = null;
            loader.UnLoad();
            loader = null;
            return false;
        }

        md5.Clear();
        loader.UnLoad();
        return true;
    }

    // 清空文件
    public void Clear()
    {
        if (m_FileEPacket != null)
        {
            m_FileEPacket.Clear();
            m_FileEPacket = null;
        }
    }
}